package com.lagou.code.controller;

import com.lagou.code.service.MailFeignClient;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/code")
public class CodeController {

    @Autowired
    public MailFeignClient mailFeignClient;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/validate/{email}/{code}")
    public Integer validateEmailCode(@PathVariable(value = "email") String email, @PathVariable(value = "code") String code) {

        System.out.println("validate code from email: " + email);

        String s = redisTemplate.opsForValue().get(email);
        System.out.println("validateEmailCode    " + s);
        if (StringUtils.isEmpty(s)) {
            return 2;
        } else {
            if (s.equals(code)) {
                return 0;
            } else {
                return 1;
            }
        }

    }


    @GetMapping("/create/{email}")
    public Integer sendEmailCode(@PathVariable String email) {

        System.out.println("send code to email" + email);

        String mailCode = RandomStringUtils.randomNumeric(6);

        //放入缓存
        redisTemplate.opsForValue().set(email, mailCode, 15, TimeUnit.MINUTES);

        mailFeignClient.sendEmail(email, mailCode);

        return 0;
    }
}
